<template>
    <el-drawer width="16vw" class="flex-drawer" direction="rtl" :close-on-click-modal="false" :modelValue="visible" @close="handleClose"  >
        <template #header>
            <div style="font-size:var(--18FontSize); font-weight:500; color:#525866;">上报整改登记</div>
        </template>
        <el-form class="flex-form" ref="myForm" :model="form" :rules="rules" label-position="top">
            <el-form-item label="巡检对象" prop="targetId">
                <FlexSelect :data="objectSelectOpt" :payload="objectList" :total="objectTotal" :form="form" @search="fetchObjectList" />
            </el-form-item>
            <el-form-item label="巡检项名称" prop="itemTargetId">
                <FlexSelect :payload="inspectionList" :data="inspectionOpt" :total="inspectionTotal" :form="form" @search="fetchInspection" />
            </el-form-item>
            <el-form-item v-if="hasValue" :label="form.valueName" prop="value" >
                <FlexInput :data="{ paramKey:'value', suffix:()=> form.valueUnit  }" :form="form" />
            </el-form-item>
            
            <el-form-item label="问题照片/视频">
                <CustomUpload ref="uploadRef" text2="图片|视频" :allowTypes="allowTypes" size="small" :maxSize="100" prop="files" :maxNumber="3" @on-select="handleSelect" />
            </el-form-item>
            <el-form-item label="问题描述" prop="problemDescription">
                <FlexInput :data="{ paramKey:'problemDescription', type:'textarea' }" :form="form" />
            </el-form-item>
            
        </el-form>
        <div style="display:flex; gap:var(--mPadding); margin-top:var(--lPadding); ">
            <div class="flex-btn middle opacity" style="flex:1;" @click="handleClose">取消</div>
            <div class="flex-btn middle" style="flex:1;" @click="handleSubmit">确认</div>
        </div>
    </el-drawer>
</template>

<script setup>
    import { watch, ref, reactive, nextTick, onMounted, onUnmounted } from 'vue';
	import { getObjectList, delObject } from '@/api/object.js';
    import { getTplInspectionList } from '@/api/tpl.js'; 
    import { addOrUpdateCorrection } from '@/api/correction.js';
    import { ElMessage } from 'element-plus';
    import FlexInput from '@/components/FlexInput.vue';
    import FlexSelect from '@/components/FlexSelect.vue';
    import CustomUpload from '@/components/CustomUpload.vue';
    const props = defineProps({
        visible:{ type:Boolean }
    });
    const emit = defineEmits(['update:visible', 'refresh']);
    const uploadRef = ref();
    const hasValue = ref(false);
    const objectList = ref([]);
    const objectSelectOpt = { paramKey:'targetId', searchPlaceholder:'输入巡检对象查询', fullWidth:true, hasSearch:true, searchType:'remote', searchKey:'targetName', hasPagination:true, labelKey:'targetId', labelName:'targetName'  };
    const objectTotal = ref(0);
    const inspectionList = ref([]);
    const inspectionTotal = ref(0);
    const inspectionOpt = { paramKey:'itemTargetId', fullWidth:true, hasPagination:true, labelKey:'itemTargetId', labelName:'itemName' };
    const allowTypes = ['jpg', 'jpeg', 'png', 'mp4', 'ogg', 'flv', 'avi', 'wmv'];
    const myForm = ref(null);
    const form = reactive({
        targetId:'',
        itemTargetId:'',   
        files:'',
        problemDescription:'',
        valueName:'',
        valueUnit:'',
        value:''
    });
    const rules = reactive({
        targetId:[{ required:true, message:'巡检对象不能为空',  trigger:'blur' }],
        itemTargetId:[{ required:true, message:'巡检项不能为空',  trigger:'blur' }],
        problemDescription:[{ required:true, message:'问题描述不能为空',  trigger:'blur' }],
        value:[{ required:true, message:'记录值不能为空',  trigger:'blur' }],
    });
    watch(()=>form.targetId, ()=>{
        // 清空巡检项的选中状态值
        form.itemTargetId = '';
        if ( form.targetId ) {
            fetchInspection();
        }
    })
    watch(()=>form.itemTargetId, ()=>{
        // console.log('itemTargetId...', form.itemTargetId);
        let obj = inspectionList.value.filter(i=>i.itemTargetId === form.itemTargetId )[0];
        if ( obj ) {
            hasValue.value = obj.needValueRemark === 1 ? true : false;
            form.valueName = obj.valueName || '未知' ;
            form.valueUnit = obj.valueUnit || '';

        }
    })
    // 重置状态
    function handleClose(){
        Object.keys(form).forEach(key=>{
            form[key] = '';
        })
        myForm.value.clearValidate();
        if ( uploadRef.value && uploadRef.value.clear ) {
            uploadRef.value.clear();
        }
        emit('update:visible', false);
    }
    function handleSubmit(){
        myForm.value.validate(valid=>{
            if ( valid ){      
                let obj = { 
                    targetId:form.targetId,
                    itemTargetId:form.itemTargetId,
                    problemDescription:form.problemDescription,
                };
                if (form.files && form.files.length ) {
                    obj.filePath = form.files.split(';');
                }
                if ( form.value ) {
                    obj.value = form.value;
                }
                addOrUpdateCorrection(obj, false)
                .then(res=>{
                    if ( res.data.code === 200 ) {
                        ElMessage({
                            type:'success',
                            message:'上报整改成功'
                        });
                        handleClose();
                        emit('refresh');
                    }
                }) 
            }                                        
        })
    }
    const handleSelect = (name, path)=>{
        form[name] = path;
    }
    
    const fetchObjectList = (params)=>{
		// 实际的axios请求;
		params = params || { page:1, pageSize:10 };
		let realParams = {};
		Object.keys(params).forEach(key=>{
			if ( params[key] ) {
				realParams[key] = params[key];
			}
		})
		getObjectList(realParams)
		.then(res=>{
			if ( res.data.code === 200 ){
				objectList.value = res.data.data;
				objectTotal.value = res.data.total;
			}
		})
	};
    const fetchInspection = (params)=>{
	    // 实际的axios请求;
	    params = params || { page:1, pageSize:10 };
        params.targetId = form.targetId;    
	    getTplInspectionList(params, true)
	    .then(res=>{
	    	if ( res.data.code === 200 ){
	    		inspectionList.value = res.data.data;
	    		inspectionTotal.value = res.data.total;
	    	}
	    })
	};
    
    onMounted(()=>{
        fetchObjectList();
    })
</script>
